const PENDING = "PENDING"; // 等待
const RESOLVED = "RESOLVED"; // 成功
const REJECTED = "REJECTED"; // 失败

// Vue响应式原理如何实现
// Vue依赖收集是什么  什么是dep 什么是watcher(在vue中什么代表watcher)
// Vue $nextTick 底层如何实现
// Vue $set 底层如何实现
// Vue diff算法原理 diff算法时间复杂度多少（O(n3)）如何优化到O(n)(O(n))
// Vue diff和React Diff区别
// React fiber架构原理

class MyPromise {
    constructor(callback) {
        this.status = PENDING; // 初始状态
        this.value = '';
        this.error = '';
        this.successList = [];
        this.errorList = [];
        const resolve = (val) => {
            // Promise概念状态一旦改变不能再次改变
            if (this.status === PENDING) {
                this.status = RESOLVED; // 改边状态 
            }
            this.value = val;
            this.successList.forEach(item => item(val))
            this.successList = []
        }
        const reject = (err) => {
            if (this.status === PENDING) {
                this.status = REJECTED;
            }
            this.error = err;
            this.errorList.forEach(item => item(err))
            this.errorList = []
        }
        callback(resolve, reject)
    }
    then(success, error) {
        return new MyPromise((resolve, reject) => {
            // 如何链式调用
            if (this.status === RESOLVED) {
                const x = success(this.value); // x 可能是 数据  也可能promise
                resolvePromise(x, resolve, reject) // 判断x是promise还是数据  如果是数据则返回  否则等待Promise完毕在返回
            }
            if (this.status === REJECTED) {
                const x = error(this.error)
                resolvePromise(x, resolve, reject)

            }
            // PENDING 说明有异步 
            if (this.status === PENDING) { // 发布订阅
                // 为什么存个箭头函数呢？  因为我不希望它立即执行 而是暂存起来
                this.successList.push(() => {
                    const x = success(this.value)
                    resolvePromise(x, resolve, reject)
                })
                this.errorList.push(() => {
                    const x = error(this.value)
                    resolvePromise(x, resolve, reject)
                })
            }
        })
    }
    all() { }
    race() { }
    static resolve() { }
    static reject() { }
}
function resolvePromise(x, resolve, reject) {
    // 如果是数据我们就直接返回
    // 如果是Promise我们就等待Promise结束再去 Resolve或者Reject
    if (typeof x === 'object' && x.then) {
        x.then((val) => {
            resolve(val)
        }, (err) => {
            reject(err)
        })
    } else {
        resolve(x)
    }
}




const p1 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
        resolve(123123)
    }, 1000)
})

p1.then((res) => {
    console.log(res, 'res')
    // return 123 ==== Promise.resolve(123)
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(123)
        }, 1000)
    })
}, err => {
    console.log(err, 'err')
}).then((res) => {
    // 如何链式调用
    console.log(res, 'res 链式')
})